<template>
  <div class="app-container">
    <h3>地推管理</h3>
    <!-- {{ $store.getters.button }}
    {{ permissionList }} -->
    <div v-if="setPermissionBtn('/findSaleUserList', searchBtn)" class="inputBox">
      <el-input v-model="search.name" class="input" placeholder="请输入姓名查询" style="width:140px" />
      <el-cascader
        ref="city"
        v-model="cityCode"
        :options="options"
        :separator="'-'"
        :disabled="tinymceDis"
        placeholder="请选择所在地区"
        size="large"
        @change="handleChange"/>
      <el-select v-model="search.gender" placeholder="请选择性别" style="width:120px">
        <el-option :value="0" label="女" />
        <el-option :value="1" label="男" />
      </el-select>

      <el-date-picker
        v-model="search.startTime"
        class="startDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择开始日期"/>
      <el-date-picker
        v-model="search.endTime"
        class="endDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择结束日期"/>
      <el-select v-model="search.status" placeholder="请选择状态" style="width:120px">
        <el-option :value="0" label="停用" />
        <el-option :value="1" label="启用" />
      </el-select>

      <el-button type="primary" class="ml10" @click="toSearch">{{ searchBtn.btnName }}</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
    </div>
    <el-button v-if="setPermissionBtn('/addSaleUser', addBtn)" type="primary" class="addBtn" @click="toaddPage()">{{ addBtn.btnName }}</el-button><br><br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <template slot="empty">
        <div class="noData">暂无数据</div>
      </template>
      <el-table-column align="center" label="序号" width="100">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="80">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="性别" width="80">
        <template slot-scope="scope">
          {{ scope.row.gender | genderStr }}
        </template>
      </el-table-column>
      <el-table-column label="所在城市">
        <template slot-scope="scope">
          <!-- {{ scope.row.province | provinceCodeStr }}{{ scope.row.county | countyCodeStr }} -->
          {{ scope.row.myCity | cityCodeStr }}
        </template>
      </el-table-column>
      <el-table-column label="手机号码" width="110">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ scope.row.status | statusStr }}
        </template>
      </el-table-column>
      <el-table-column label="开通时间" width="170">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="290">
        <template slot-scope="scope">
          <el-button
            v-if="setPermissionBtn('edit', scope.row)"
            :disabled="scope.row.status === 0"
            value="编辑"
            size="mini"
            type="primary"
            @click="editRow(scope)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('enable/disable', scope.row)"
            :type="scope.row.status == 0?'success':'danger'"
            size="mini"
            value="启用/停用"
            @click="statusRow(scope, scope.row.status)"
            v-html="splitName(scope.row.btnName, scope.row.status)"/>
          <el-button
            v-if="setPermissionBtn('/findMyMemberList', scope.row)"
            size="mini"
            value="查看推广会员"
            type="success"
            @click="promotion(scope)">{{ scope.row.btnName }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <!-- <detail :detialvisible.sync="dialogTableVisible" :dialogdata.sync="list" :myindex.sync="detailIndex" :detail-mode="'menberManage'" /> -->
    <!-- <remark :remark-list="remarkList" :remark-visible.sync="remarkVisible" :remark-index="remarkIndex" />
    <remarkPropt
      ref="remarke"
      :remark-propt-list="remarkProptList"
      :remark-propt-visible.sync="remarkProptVisible"
      :remark-propt-index="remarkProptIndex"
      :cash-type="cashType"
      @remarkText="remarkText" /> -->
  </div>
</template>

<script>
import { teacherCashRecordUpdate, checkRemark, teacherCashRecord, getUserMessage } from '@/api/financial'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import detail from '@/components/detail'
import remark from '@/components/remark'
import remarkPropt from '@/components/remark/remarkPrompt'
import { getByteLength } from '@/utils/validate'
import { checkNotEmail, checkNum } from '@/utils/validateUtil';
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { findSaleUserList, updateSaleUser } from '@/api/user'
import { getPermission } from '@/api/permission'

import { provinceAndCityData, regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { getLocalUserName, setLocalUserName } from '@/utils/uid'

const inputValidatorNum = (v) => {
  console.log(getByteLength(v))
  if (getByteLength(v) > 600) {
    return false
  }
}

export default {
  components: { Pagination, detail, remark, remarkPropt },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    genderStr(gender) {
      const genderMap = {
        0: '女',
        1: '男'
      }
      return genderMap[gender]
    },
    statusStr(status) {
      const statusMap = {
        0: '停用',
        1: '启用'
      }
      return statusMap[status]
    },
    cityCodeStr(cityCode) {
      return CodeToText[[cityCode]]
    },
    countyCodeStr(countyCode) {
      return CodeToText[[countyCode]]
    },
    provinceCodeStr(provinceCode) {
      return CodeToText[[provinceCode]]
    }

  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 0,
        pageSize: 10
      },
      options: regionData,
      tinymceDis: false,
      cityCode: [],
      search: {
        name: '',
        gender: '',
        phone: '',
        province: '',
        city: '',
        county: '',
        startTime: '',
        endTime: ''
      },
      addBtn: {},
      searchBtn: {},
      userName: '',
      permissionList: [] // 权限数据列表
    //   permissionShow: false, // 权限数据未到达之前按钮隐藏

    }
  },
  computed: {
    setPermissionBtn() {
      return function(str, row) {
        let index = -1
        const buttonList = this.$store.getters.button
        index = buttonList.findIndex(item => item.value === str)
        // console.log(index)
        if (index !== -1) {
          row.btnName = buttonList[index].name
          return true
        } else {
          return false
        }
      }
    },
    splitName() {
      return function(name, status) {
        console.log('name:', name)
        console.log('status:', status)
        const nameArr = name.split('/')
        if (status === 0) {
          return nameArr[0]
        } else {
          return nameArr[1]
        }
      }
    }
  },
  watch: {
    '$store.getters.button'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  created() {
    this.fetchData()
    this.userName = getLocalUserName()
    // this.getPermissonFn()
  },
  mounted() {
    // console.log('mounted & getPermissonFn:', this.getPermissonFn())
    this.getPermissonFn() // 获取按钮权限 vuex的button

    // console.log(this.$store.getters.button)
    // console.log('permissionList:', this.permissionList)
  },
  methods: {
    toaddPage() {
      this.$router.push({
        path: 'add',
        query: {}
      })
    },
    // 省市
    handleChange(value) {
      // this.tRuleForm.province = value[0] // CodeToText[value[0]]
      // this.tRuleForm.city = value[1] // CodeToText[value[1]]
      // this.resList.province = CodeToText[value[0]]
      // this.resList.city = CodeToText[value[1]]
      // this.resList.city = [CodeToText[value[0]], CodeToText[value[1]], CodeToText[value[2]]]
      // this.resList.city = [value[0], value[1], value[2]]
      this.search.province = value[0]
      this.search.city = '' // value[1]
      this.search.county = '' // value[2]
      //  console.log('1:', this.resList.province, this.resList.city)
      console.log(this.search.province, this.search.city, this.search.county)
    },
    // 点击推广会员
    promotion(scope) {
      // const _this = this;
      // const object = Object.assign({ isEdit: true }, scope.row)
      console.log(scope)
      this.$router.push({
        path: 'list',
        query: scope.row
      })
    },
    // 停用启用的方法
    statusRow(row, num) {
      const strAsk = num === 0 ? '是否启用？' : '是否停用？'
      const str = num === 0 ? '已启用' : '已停用'
      this.$confirm(strAsk, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        // console.log(row.row.id, num)
        num === 0 ? num = 1 : num = 0
        const newData = Object.assign({ status: num }, { id: row.row.id })
        // console.log(newData)
        updateSaleUser(newData).then(response => {
        // console.log('修改状态：', response)
          if (Number(response.code) === 200) {
            this.fetchData()
            Message.success(str);
          } else {
            Message.error(response.message + '-' + response.data)
          }
        })
      })
    },
    // 编辑
    editRow(row) {
      const _this = this;
      const object = Object.assign({ isEdit: true }, row.row)
      console.log(row)
      this.$router.push({
        path: 'add',
        query: object
      })
    },
    // 查询
    toSearch() {
      if (this.search.startTime && this.search.endTime) {
        const start = new Date(this.search.startTime).getTime();
        const end = new Date(this.search.endTime).getTime();
        if (start > end) {
          Message.error('结束时间必须大于开始时间')
          return false
        }
      }
      if (this.search.startTime && this.search.startTime.indexOf(' 00:00:00') === -1) this.search.startTime += ' 00:00:00'
      if (this.search.endTime && this.search.endTime.indexOf(' 23:59:59') === -1) this.search.endTime += ' 23:59:59'
      //   console.log(this.search.startTime + ' 00:00:00')
      //   console.log(this.search.endTime + ' 23:59:59')
      //   console.log(this.formatDateMinute(this.search.startTime))
      //   console.log(this.formatDateMinute(this.search.endTime))
      this.listLoading = true
      const newData = this.$deleteNull(this.objectCon(this.listQuery, this.search))
      console.log(newData)
      findSaleUserList(newData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 显示城市 如果是北京天津， 不显示市辖区， 显示北京天津
    formatCity(list) {
      list.forEach(item => {
        if (item.province === '110000' || item.province === '120000') {
          item.myCity = item.province
        } else {
          item.myCity = item.city
        }
      })
    },
    fetchData() {
      this.listLoading = true
      // const newData = this.objectCon(this.listQuery, this.search)
      const newData = this.$deleteNull(this.objectCon(this.listQuery, this.search))
      console.log(newData)
      findSaleUserList(newData).then(response => {
        if (response.code === '200') {
          this.list = response.data.list
          this.total = response.data.total
          this.formatCity(this.list)
          console.log(this.list)
          setTimeout(() => {
            this.listLoading = false
          }, 0.5 * 1000)
        } else {
          Message.error(response.message + '-' + response.data)
        }
      })
    },
    // 重置
    toReset() {
      this.search.name = ''
      this.search.gender = ''
      this.search.phone = ''
      this.search.province = ''
      this.search.city = ''
      this.search.county = ''
      this.search.status = ''
      this.cityCode = []
      this.search.startTime = ''
      this.search.endTime = ''
    }
    // 备注
    // changeRemarks(id, index) {
    //   this.remarkProptIndex = index
    //   console.log('--->', id)
    //   let userData = ''
    //   this.remarkProptVisible = true
    //   this.$refs.remarke.request(id)
    //   // console.log('==>'+JSON.stringify(this))
    //   checkRemark(id).then(res => {
    //     userData = res.data
    //     // console.log(userData)
    //     this.remarkProptList = userData
    //     this.remarkProptVisible = true
    //   })
    // },
    // 驳回
    // rejectFn(id) {
    //   console.log()
    //   this.$prompt('请输入驳回理由', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     inputPlaceholder: '请输入驳回理由',
    //     inputValidator: inputValidatorNum,
    //     inputErrorMessage: '最多输入200个字符'
    //   }).then(({ value }) => {
    //     const data = { id, remark: value, status: 3, type: this.cashType } // type1. 提现 2.打款
    //     teacherCashRecordUpdate(data).then(res => {
    //       console.log(res)
    //       if (res.code === '200') {
    //         this.fetchData();
    //         this.$message({
    //           type: 'success',
    //           message: '已驳回!'
    //         });
    //       } else {
    //         this.$message.error(res.message + '-' + res.data)
    //         this.fetchData();
    //       }
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '取消输入'
    //     })
    //   })
    // },
    // 点击审核 - 待审核：点击审核按钮，审核通过后，状态变为“待放款”
    // waitCheck(id) {
    //   this.$confirm('提款请求是否审核通过？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     const data = { id, status: 1, type: this.cashType } // type1. 提现 2.打款
    //     teacherCashRecordUpdate(data).then(res => {
    //       console.log(res)
    //       if (res.code === '200') {
    //         this.fetchData();
    //         this.$message({
    //           type: 'success',
    //           message: '审核成功!'
    //         });
    //       } else {
    //         this.$message.error(res.message + '-' + res.data)
    //         this.fetchData();
    //       }
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '已取消审核'
    //     })
    //   })
    // },

    // 查看备注
    // checkRemark(id, index) {
    //   checkRemark(id).then(res => {
    //     if (res.code === '200') {
    //       this.remarkList = res.data
    //       if (this.remarkList.length) {
    //         this.remarkVisible = true
    //         this.remarkIndex = index
    //       } else {
    //         this.$message('暂无备注');
    //       }
    //     }
    //   })
    // },
    // 打款
    // getCash(id) {
    //   this.$confirm('是否确认打款?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     const data = { id, status: 2, type: this.cashType } // type1. 提现 2.打款
    //     teacherCashRecordUpdate(data).then(res => {
    //       if (res.code === '200') {
    //         this.fetchData();
    //         this.$message({
    //           type: 'success',
    //           message: '打款成功!'
    //         });
    //       } else {
    //         this.$message.error(res.message + '-' + res.data)
    //         this.fetchData();
    //       }
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '已取消打款'
    //     })
    //   })
    // },
    // 点击详情
    // detail(index) {
    //   this.detailIndex = index
    //   this.dialogTableVisible = true
    // },
    // addCourse(courseTypeId) {
    //   this.$data.courseTypeId = courseTypeId
    //   this.$data.dialogFormVisible = true
    // },
    // getValue(value) {
    //   this.$data.temp.status = value
    // },
    // getEnable(value) {
    //   this.$data.course.isEnable = value
    // },
    // getChildren(value) {
    //   this.$data.course.courseList = value
    // },
    // addCourseType() {
    //   this.$router.push({
    //     path: 'add',
    //     query: { isEdit: false }
    //   })
    // }

  }
}
</script>

<style lang="scss" scoped>
  .el-icon-remove {
    margin-left: 10px;
  }
  .img_url {
    width: 110px;
    height: 110px;
  }
  .inputBox{
    div{ margin-bottom: 10px;}
    .input:nth-of-type(1){ width: 160px;}
    .input:nth-of-type(2){ width: 140px;}
    .input:nth-of-type(3){ width: 160px;}
    .teacherType { width: 150px;}
    .teacherSex { width: 120px;}
    .startDate { width: 150px;}
    .endDate { width: 150px;}
    .teacherStatus { width: 150px;}
  }
</style>
